package com.ck.company.controller;

import com.ck.company.service.CpVideoService;
import com.ck.config.CustomProperties;
import com.ck.constant.FileConstant;
import com.ck.constant.RequestConstant;
import com.ck.constant.ResponseConstant;
import com.ck.exception.ControllerException;
import com.ck.model.common.User;
import com.ck.model.common.Video;
import com.ck.model.common.page.PageInfo;
import com.ck.model.common.sys.JsonResponse;
import com.ck.model.company.vo.CpVideoListVO;
import com.google.common.collect.Lists;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * @author dxy
 * @date 2018/7/3 18:03
 */
@Controller
@RequestMapping("/cpVideo")
public class CpVideoController {
	private static Logger logger = LoggerFactory.getLogger(CpVideoController.class);
	@Autowired
	private CpVideoService cpVideoService;
	@Autowired
	private CustomProperties customProperties;

	/**
	 * 上传视频
	 */
	@ResponseBody
	@RequestMapping("/upload")
	public Object uploadVideo(@RequestParam("files") MultipartFile files, HttpServletRequest request) {
		try {
			logger.info("Running in uploadVideo：" + files);
			//视频全名（包含扩展名）
			String originalFilename = files.getOriginalFilename();
			if (StringUtils.isBlank(originalFilename)) {
				return  new JsonResponse(ResponseConstant.CODE_FAIL, "视频名称不能为空");
			}
            if (files.getSize() > customProperties.getMaxVideoSize()) {
                return new JsonResponse(ResponseConstant.CODE_FAIL, "只能上传视频文件，且不超过"
                        + (customProperties.getMaxVideoSize() / 1024 / 1024) + "M");
            }
			//视频后缀
			String extension = FilenameUtils.getExtension(originalFilename);
			//验证后缀名
			if (!FileConstant.VIDEO_SUFFIX_LIST.contains(extension)) {
				return  new JsonResponse(ResponseConstant.CODE_FAIL, "文件格式不正确，请上传视频文件");
			}
			//视频名称
			String videoName = originalFilename.replaceAll("." + extension, "");
			if (StringUtils.isBlank(videoName.trim())) {
				return  new JsonResponse(ResponseConstant.CODE_FAIL, "视频名称不能为空");
			}
			List msgList = Lists.newArrayList();
			Map<String, Object> msgMap = cpVideoService.saveVideo(files, request);
			msgList.add(msgMap);
			return msgList;
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("CpVideoController uploadVideo 上传视频失败：" + e.getMessage());
			return new ControllerException("上传视频失败： " + e.getMessage());
		}
	}

	/**
	 * 重命名
	 */
	@ResponseBody
	@RequestMapping("/rename")
	public Object renameVideo(String videoNewName, Long videoId, HttpServletRequest request) {
		//验证新输入视频名称不能为空
		if (StringUtils.isBlank(videoNewName)) {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "视频名称不能为空");
		}
		//验证视频ID不能为空
		if (videoId == null) {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "视频名称ID不能为空，请联系管理员");
		}
		try {
			//获取用户的company_code
			User loginUser = (User) request.getSession().getAttribute(RequestConstant.SESSION_KEY_USER);
			String companyCode = loginUser.getCompanyCode();
			//查看视频名称是否重复
			Video video = cpVideoService.getVideoByName(companyCode, videoNewName);
			if (video != null) {
				return  new JsonResponse(ResponseConstant.CODE_FAIL, "视频名称已存在");
			}
			cpVideoService.renameVideo(videoNewName, videoId, request);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("CpVideoController renameVideo 重命名失败：" + e.getMessage());
			return e;
		}
		return "";
	}

	/**
	 * 视频列表
	 */
	@RequestMapping("/list")
	public String listVideo(String videoName, Integer pageNum, Integer pageSize, Model model, HttpServletRequest request) {
		User loginUser = (User) request.getSession().getAttribute(RequestConstant.SESSION_KEY_USER);
		String companyCode = loginUser.getCompanyCode();
		PageInfo<CpVideoListVO> pageInfo = cpVideoService.listVideo(companyCode, videoName, pageNum, pageSize);
		model.addAttribute("videoName", videoName);
		model.addAttribute("videoList", pageInfo.getList());
		model.addAttribute("pageNum", pageInfo.getPageNum());
		model.addAttribute("pageSize", pageInfo.getPageSize());
		model.addAttribute("total", pageInfo.getTotal());
		return "cp/cp_video_list";
	}

	/**
	 * 删除视频
	 */
	@ResponseBody
	@RequestMapping(value = "/delete")
	public Object deleteVideo(Long videoId, HttpServletRequest request) {
		if (videoId == null) {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "视频ID不能为空，请联系管理员");
		}
		try {
			cpVideoService.deleteVideoById(videoId, request);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("CpVideoController deleteVideo 删除视频失败：" + e.getMessage());
			return e;
		}
		return "";
	}
}
